import React, { useState, useEffect, useRef } from 'react'
import { Popconfirm, Button, Modal, Form, Input, Select } from 'antd';
import { connect } from 'dva';
import { ProTable } from '@ant-design/pro-components';

const LabelManage = ({ labelList, dispatch, classifyList }) => {
  useEffect(() => {
    tableRef.current?.reload()// 刷新表格
  }, [labelList]);
  const tableRef = useRef();
  const [form] = Form.useForm();
  const [status, setStatus] = useState('');
  const [currentTag, setCurrentTag] = useState(null);
  const [isModal, setIsModal] = useState(false)// 控制弹窗显与隐
  const columns = [
    {
      title: '标签id', dataIndex: 'tagId', key: 'tagId', align: 'center', search: false,
      sorter: (a, b) => a.tagId - b.tagId
    },
    { title: '标签名称', dataIndex: 'tagName', key: 'tagName', align: 'center', },
    {
      title: '分类名称', dataIndex: 'categoryName', key: 'categoryName', align: 'center',
      render: (_, record) => record.categoryName.join('、')
    },
    { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center', search: false, },
    {
      title: '操作', key: 'tagInfo', align: 'center', search: false,
      render: (_, data) => {
        return (
          <>
            <Button key={'editTag'} type='link'
              onClick={() => {
                setCurrentTag(data); setStatus('edit');
                setIsModal(true); form.setFieldsValue(data)
              }}>编辑</Button>
            <Popconfirm
              title="确定要删除该标签吗？"
              onConfirm={() => {
                dispatch({
                  type: 'labelManage/delTag',
                  payload: {
                    tagId: data.tagId,
                  },
                })
              }} okText="确定" cancelText="取消">
              <Button danger type='link' key="delect" >删除</Button>
            </Popconfirm>
          </>
        );
      }
    },
  ];

  const reloadTable = () => {
    dispatch({
      type: 'labelManage/queryTag',
    })
  }

  return <>
    <ProTable actionRef={tableRef} defaultData={labelList} columns={columns} rowKey="labelList"
      pagination={{
        defaultPageSize: 10, // 默认每页显示10条数据
        showSizeChanger: true, // 显示每页显示条数的选择器
        pageSizeOptions: ['10', '20', '50'], // 可供用户选择的每页显示条数选项
      }}
      options={{ reload: reloadTable, setting: true, density: true, }}
      toolBarRender={() => [<Button type="primary" onClick={() => { setIsModal(true), setStatus('add') }}>新建</Button>]}
      request={(params, sort, filter) => {
        return Promise.resolve({
          data: () => {
            return labelList?.filter((item) => {
              let result = true;
              Object.entries(params).forEach(([key, value]) => {
                if (key == "current" || key == "pageSize") {
                  return;
                }
                const dataKey = key.replace("search", "")
                if (item.hasOwnProperty(dataKey)) {
                  result = (result && item[dataKey].indexOf(value) != -1)
                }
              })
              return result;
            });
          },
          success: true,
        });
      }} />;
    {/*form.resetFields();：当用户取消编辑或创建新条目时，你可能希望清除表单并使其回到空白状态。 */}
    <Modal key="updateModal" title={status === 'add' ? '新建标签' : '编辑标签'}
      open={isModal} onCancel={() => { setIsModal(false); form.resetFields(); }} maskClosable={false}
      footer={[
        <Button key="submit" type="primary" onClick={() => form.submit()}>提交</Button>,
        <Button key="back" onClick={() => { setIsModal(false); form.resetFields(); }}>取消</Button>,
      ]}>
      <Form form={form} name="basic" labelCol={{ span: 6, }} wrapperCol={{ span: 16, }} onFinish={values => {
        dispatch({
          type: status === 'add' ? 'labelManage/addTag' : 'labelManage/updateTag',
          payload: { ...values, tagId: currentTag?.tagId }
        });
        setIsModal(false);
        form.resetFields();
      }}>
        <Form.Item label="标签名称" name="tagName" rules={[
          {
            required: true,
            message: '请输入你想要添加的标签名称!',
          },
          {
            pattern: /^[\u4e00-\u9fa5A-Za-z0-9+]+$/,
            message: '标签名称不可用!',
          },
          {
            pattern: /^.{2,30}$/,
            message: '标签长度为2-30位!',
          }
        ]}>
          <Input /></Form.Item>
        <Form.Item label="分类名称" name="categoryId" rules={[
          {
            required: true,
            message: '请选择分类!',
          },
        ]}>
          <Select mode="multiple" placeholder="请选择分类" allowClear
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={classifyList.map(option => ({ value: option.categoryId, label: option.categoryName }
            ))}>
          </Select></Form.Item>
      </Form>
    </Modal>{
    }
  </>
}

export default connect(({ labelManage, classifyManage }) => ({
  labelList: labelManage.labelList,
  classifyList: classifyManage.classifyList,
}))(LabelManage);
